package com.brite.android.game.action;

import java.util.ArrayList;
import java.util.Random;

import org.anddev.andengine.audio.music.Music;
import org.anddev.andengine.audio.music.MusicFactory;
import org.anddev.andengine.audio.sound.Sound;
import org.anddev.andengine.audio.sound.SoundFactory;
import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.Camera;
import org.anddev.andengine.engine.handler.IUpdateHandler;
import org.anddev.andengine.engine.handler.timer.ITimerCallback;
import org.anddev.andengine.engine.handler.timer.TimerHandler;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.CameraScene;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.shape.IShape;
import org.anddev.andengine.entity.sprite.AnimatedSprite;
import org.anddev.andengine.entity.sprite.Sprite;
import org.anddev.andengine.entity.text.ChangeableText;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;
import org.anddev.andengine.opengl.texture.region.TiledTextureRegion;
import org.anddev.andengine.sensor.accelerometer.AccelerometerData;
import org.anddev.andengine.sensor.accelerometer.IAccelerometerListener;
import org.anddev.andengine.ui.activity.BaseGameActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Vibrator;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.badlogic.gdx.math.Vector2;
import com.brite.android.game.R;
import com.brite.android.game.Wellcome;
import com.brite.android.game.achievement.model.data.dao.RankViewDAO;
import com.brite.android.game.achievement.model.orm.RankView;
import com.brite.android.game.menu.MainMenu;

public class MainGame extends BaseGameActivity implements
		IAccelerometerListener {
	
	private int CAMERA_WIDTH;
	private int CAMERA_HEIGHT;
	private Camera mCamera;

	Display display;
	private Music bgMusic;
	private Sound bgSound;
	private boolean enableBgMusic;
	private boolean enableBgSound;
	private boolean enableVibrate;
	private Scene scene;

//	private boolean STATUS_GAME_CURRENT = true;
	
	private float timeToEnemyAppear = 2f;
	private float timeToLineEnemyAppear = 20f;
	
	LayoutInflater factoryWhenFinishGame;
	View gameInfoFinish;
	EditText playerNameWhenFinishGame;
	TextView currentScoreWhenFinishGame;
	TextView currentNumberKillWhenFinishGame;
	TextView bestScoreWhenFinishGame;
	TextView bestNumberKillWhenFinishGame;
	
	LayoutInflater factoryWhenPauseGame;
	View gameInfoWhenPauseGame;
	TextView playerNameWhenPauseGame;
	TextView currentScoreWhenPauseGame;
	TextView currentNumberKillWhenPauseGame;
	TextView bestScoreWhenPauseGame;
	TextView bestNumberKillWhenPauseGame;
	
	
	String backgroundPath = new String();
	private Texture bgTexture;
	private TextureRegion bgTextureRegion;

	private Texture monsterKilledTexture;
	private TiledTextureRegion monsterKilledRegion;
	private ChangeableText monsterKilledText;
	private AnimatedSprite monsterKilledWhenPlaying;
	
	private Texture fontScoreTexture;
	private Font txtFontScore;
	private ChangeableText score;
	private final long maxScore = 1000000000;
	private int hitCount;
	private long hitScore;
	private Texture fontComboKillTexture;
	private Font txtFontComboKill;
	private ChangeableText scoreDurationCombo;
	TimeCounter comboCounter;
	private int hitComboCount;
	private int scorePerEnemyKilled = 7;
	private static final float TimerCombo = 2f;
	SharedPreferences pre;
	public static RankViewDAO rankViewDAO;
	private RankView bestRankView;
	AnimatedSprite playerWhenDied;
	private TimeCounter timeToActiveDialogSaveScore = new TimeCounter(1.5f);
	
	private ArrayList<Enemy> arrListEnemyDied = new ArrayList<Enemy>();
	
	// Boss
//	private int countHitBoss = 0;
//	private long lastCurrentScore = 0;
//	private int countBoss = 0;
	
	// End Boss
	
	// Line Enemy
	private float magnitudePlayer;
	private float lengLineEnemy;
	private float increaseX, increaseY; 
	private ArrayList<Enemy> arrLineEnemy = new ArrayList<Enemy>();
//	private int countLineEnemy = 0;
	private long lastTeamEnemy;
	
	public static final int CORDINATE_1 = 1;
	public static final int CORDINATE_2 = 2;
	public static final int CORDINATE_3 = 3;
	public static final int CORDINATE_4 = 4;

	public static final int ROTATE_0 = 1;
	public static final int ROTATE_30 = 2;
	public static final int ROTATE_90 = 3;
	public static final int ROTATE_150 = 4;

	private final int LAYER_BACKGROUND = 1;
	private final int LAYER_ENEMY = 2;
	private final int LAYER_ITEM = 3;
	private final int LAYER_PLAYER = 4;
	private final int LAYER_ITEM_PROTECT = 5;
	private final int LAYER_STOPGAME = 6;
	
	int mRotateState;
//	= ROTATE_30;

	String characterPath = new String();
	String characterPathWhenDied = new String();
	private Creature mPlayer;
	private Texture mPlayerTexture;
	private TiledTextureRegion mPlayerTextureRegion;
	private Texture mPlayerDiedTexture;
	private TiledTextureRegion mPlayerDiedTextureRegion;
	
	private Texture enemyDied_Water_Texture;
	private TiledTextureRegion enemyDied_Water_TextureRegion;
	
	private Texture enemyDied_Fire_Texture;
	private TiledTextureRegion enemyDied_Fire_TextureRegion;
	
	private Texture enemyActiveTexture;
	private TiledTextureRegion enemyActiveTextureRegion;
	private Texture enemyInActiveTexture;
	private TiledTextureRegion enemyInactiveTextureRegion;
	private long[] mPlayerAnimationDuration = { 100, 100, 100, 100, 100, 100};
	private long[] mCreepAnimationDuration = { 100, 100, 100, 100, 100, 100};
	
	private long[] enemyInActiveAnimationDuration = {400, 300, 300, 200, 200, 100, 400, 300, 300, 200, 200, 100};
	
	private long[] smallItemEffectAnimationDuration = { 100, 150, 150, 200, 200, 300, 300, 200, 150};
	private long[] auxiliaryEffectAnimationDuration = { 50, 100, 150, 150, 150, 200, 200, 250, 150, 100};
	private long[] largeItemEffectAnimationDuration = {50,70,80,80,100,100,120,200,200,200,200,200,200,50,70,80,80,100,100,120,200,200,200,200};
	
	private long[] enemyIsEffectedAnimationDuration = { 100, 150, 150, 200, 200, 300, 300, 200};
	protected final float mSpeed = 40f;
	protected final float maxSpeed = 4 * mSpeed;
	protected float enemySpeed = mSpeed;
	
	float rateVelocity = 1;
	private ArrayList<Creature> arrListActiveEnemy = new ArrayList<Creature>();
	private ArrayList<Enemy> arrListInactiveEnemy = new ArrayList<Enemy>();
	private long lastTimeEnemyAppear;
	// ITEM PREPARE
	private ArrayList<Items> listItemPrepare; 
	
	// AUXILIARY ITEM - CRAZY : INCREASE VELOCITY
//	public float crazyRate = 2.f;
	
//	private Texture crazyItemTexture;
//	private TiledTextureRegion crazyItemTextureRegion;
//	private boolean crazyPlayer;
	private Texture auxiliaryItemTexture;
	private TiledTextureRegion auxiliaryItemTextureRegion;
	private Texture auxiliaryEffectItemTexture; 
	private TiledTextureRegion auxiliaryEffectItemTextureRegion;
//	private Texture auxiliaryItemEffectAfterActiveTexture;
//	private TiledTextureRegion auxiliaryItemEffectAfterActiveTextureRegion;
	private AnimatedSprite auxiliaryItemSpriteAfterActive;
	private ArrayList<ItemActive> arrListAuxiliaryItemActive = new ArrayList<ItemActive>();
	private ArrayList<Enemy> arrListEnemyAffected = new ArrayList<Enemy>();
//	private boolean isActiveAuxiliary;
//	private TimeCounter auxiliaryTimeCounter; 
//	private TimeCounter auxiliaryEffectTimeCounter;
	
	// PROTECT ITEM
	private Texture protectItemTexture;
	private TiledTextureRegion protectItemTextureRegion;
	private Texture protectEffectItemTexture;
	private TiledTextureRegion protectEffectItemTextureRegion;
	boolean protectPlayer;
	private boolean isActiveProtect;
	private TimeCounter protectTimeCounter;
	private TimeCounter protectEffectTimeCounter;
	private AnimatedSprite protectItemActive;
	
	// SMALL_SCALE_DAMAGE ITEM
	private Texture smallDamageItemTexture;
	private TiledTextureRegion smallDamageItemTextureRegion;
	private Texture smallDamageDestinationItemTexture;
	private TiledTextureRegion smallDamageDestinationItemTextureRegion;
	private Texture smallDamageEffectItemTexture;
	private TiledTextureRegion smallDamageEffectItemTextureRegion;
	private ArrayList<ItemActive> arrListSmallDamageItemActive = new ArrayList<ItemActive>();
	
	// LARGE_SCALE_DAMAGE ITEM
	private Texture largeDamageItemTexture;
	private TiledTextureRegion largeDamageItemTextureRegion;
	private Texture largeDamageEffectItemTexture;
	private TiledTextureRegion largeDamageEffectItemTextureRegion;
	private ArrayList<ItemActive> arrListLargeDamageItemActive = new ArrayList<ItemActive>();
	
	private ItemManager itemManager;
	
	private TimeCounter increaseSweepTimeCounter;
	private int reachComboCount = 0;
	private int reachSweepByCombo = 50;
	private int maxEnemyAppearAtTheSameTime = 5;
	private boolean isSweepActive = false;
	private boolean isSweepByCombo = false;
	private boolean isSweepByScore = false;
//	private float rateIncrease = 0.5f;
	private int typeSweep = 0;
	
	private Texture pauseTexture;
	private TextureRegion pauseTextureRegion;
	private Sprite clickToPauseGame;
	private Region regionClickToPauseGame;
	
	private CameraScene pauseScene;
	// Change when design
	private Texture pauseEffect;
	private TextureRegion pauseEffectTextureRegion;
	
	private boolean flag_EndGame = false; 
	private TimeCounter timeToShowDialog;
	
	private Texture enemyAffectedTexture;
	private TiledTextureRegion enemyAffectedTextureRegion;
//	private AnimatedSprite enemyIsAffected;
	
	/**
	 * Main tasks
	 */
	public Engine onLoadEngine() {
		display = getWindowManager().getDefaultDisplay();
		CAMERA_WIDTH = display.getWidth();
		CAMERA_HEIGHT = display.getHeight();

		this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		final EngineOptions engineOptions = new EngineOptions(true,
				ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(
						CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
		engineOptions.getTouchOptions().setRunOnUpdateThread(true);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		engineOptions.setNeedsMusic(true);
		engineOptions.setNeedsSound(true);
		Engine engine = new Engine(engineOptions);

		return engine;
	}

	private void prepareItem(){
		listItemPrepare = new ArrayList<Items>();
		
		// AUXILIARY ITEM
//		crazyItemTexture = new Texture(32, 32, TextureOptions.DEFAULT);
//		
//		crazyItemTextureRegion = TextureRegionFactory.createTiledFromAsset(
//				crazyItemTexture, this, "FlyShoes_1.png", 0, 0, 1, 1);
		auxiliaryItemTexture = new Texture(256, 64, TextureOptions.DEFAULT);
		auxiliaryItemTextureRegion = TextureRegionFactory.createTiledFromAsset(auxiliaryItemTexture, this, "icon_skill_water_full(40x40).png", 0, 0, 4, 1);
		
		auxiliaryEffectItemTexture = new Texture(1024, 512, TextureOptions.DEFAULT);
		auxiliaryEffectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(auxiliaryEffectItemTexture, this, "skill_waterFull(130x130)_3.png", 0, 0, 5, 2);
		
//		auxiliaryItemEffectAfterActiveTexture = new Texture(64, 64, TextureOptions.DEFAULT);
//		auxiliaryItemEffectAfterActiveTextureRegion = TextureRegionFactory.createTiledFromAsset(auxiliaryItemEffectAfterActiveTexture, this, "IceAfterActive_2.png", 0, 0, 1, 1);
		
		// PROTECT ITEM
		protectItemTexture = new Texture(256, 64, TextureOptions.DEFAULT);
		protectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(protectItemTexture, this, "icon_skill.protect_40x40.png", 0, 0, 4, 1);
		
		protectEffectItemTexture = new Texture(512, 512, TextureOptions.DEFAULT);
		protectEffectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(protectEffectItemTexture, this, "item_protect.png", 0, 0, 4, 1);
		
		// SMALL SCALE DAMAGE
		smallDamageItemTexture = new Texture(256, 64, TextureOptions.DEFAULT);
		smallDamageItemTextureRegion = TextureRegionFactory.createTiledFromAsset(smallDamageItemTexture, this, "icon_skill_fire(40x40).png", 0, 0, 4, 1);
		
		smallDamageDestinationItemTexture = new Texture(1024, 512, TextureOptions.DEFAULT);
		smallDamageDestinationItemTextureRegion = TextureRegionFactory.createTiledFromAsset(smallDamageDestinationItemTexture, this, "destination.png", 0, 0, 3, 1);
		
		smallDamageEffectItemTexture = new Texture(512, 512, TextureOptions.DEFAULT);
		smallDamageEffectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(smallDamageEffectItemTexture, this, "skill_1_Ac.png", 0, 0, 3, 3);
		
		// LARGE SCALE DAMAGE
		largeDamageItemTexture = new Texture(128, 64, TextureOptions.DEFAULT);
		largeDamageItemTextureRegion = TextureRegionFactory.createTiledFromAsset(largeDamageItemTexture, this, "icon.skill_kamejoko(40x40).png", 0, 0, 3, 1);
		
//		largeDamageEffectItemTexture = new Texture(256, 256, TextureOptions.DEFAULT);
//		largeDamageEffectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(largeDamageEffectItemTexture, this, "ShurikenActive.png", 0, 0, 1, 1);
		largeDamageEffectItemTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		largeDamageEffectItemTextureRegion = TextureRegionFactory.createTiledFromAsset(largeDamageEffectItemTexture, this, "skillKame.png", 0, 0, 4, 6);

		mEngine.getTextureManager().loadTextures(auxiliaryItemTexture, auxiliaryEffectItemTexture, protectItemTexture, protectEffectItemTexture, smallDamageItemTexture, smallDamageEffectItemTexture, largeDamageItemTexture, largeDamageEffectItemTexture);
	}
	
	private void prepareSound(){
		SoundFactory.setAssetBasePath("mfx/");
		try {
			bgSound = SoundFactory.createSoundFromAsset(
					mEngine.getSoundManager(), this, "explosion.ogg");
		} catch (Exception e) {
			e.printStackTrace();
		}

		MusicFactory.setAssetBasePath("mfx/");
		try {
			bgMusic = MusicFactory.createMusicFromAsset(
					mEngine.getMusicManager(), this,
					"wagner_the_ride_of_the_valkyries.ogg");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void loadBaseDataAndSetting(){
		pre = getSharedPreferences(Wellcome.PREFS_NAME, Context.MODE_PRIVATE);
		characterPath = pre.getString("CharacterName", "robotLive.png");
		characterPathWhenDied = pre.getString("CharacterDied", "robotDied.png");
		backgroundPath = pre.getString("MapName", "map_1.png");
		
		enableBgMusic = pre.getBoolean("music", false);
		enableBgSound = pre.getBoolean("sound", false);
		enableVibrate = pre.getBoolean("vibrate", false);
		mRotateState = pre.getInt("rotate", ROTATE_30);
		
		increaseSweepTimeCounter = new TimeCounter(7.0f);
	}
	
	// PREPARE TO SAVE RANK
	private void prepareToSaveRank(){
		// RANK
		pre = getSharedPreferences(Wellcome.PREFS_NAME, Context.MODE_PRIVATE);
		factoryWhenFinishGame = LayoutInflater.from(this);
		gameInfoFinish = factoryWhenFinishGame.inflate(R.layout.dialog_game_over, null);
		
		rankViewDAO = new RankViewDAO(this);
		rankViewDAO.getReadable();
		bestRankView = rankViewDAO.getBestRankView();
		rankViewDAO.closeConnection();
		
		playerNameWhenFinishGame = (EditText) gameInfoFinish.findViewById(R.id.playerName);
		playerNameWhenFinishGame.setText(pre.getString("userName", ""));
		
		currentScoreWhenFinishGame = (TextView) gameInfoFinish.findViewById(R.id.currentScore);
		currentNumberKillWhenFinishGame = (TextView) gameInfoFinish.findViewById(R.id.currentNumberKill);
		
		bestScoreWhenFinishGame = (TextView) gameInfoFinish.findViewById(R.id.bestScore); 
		bestNumberKillWhenFinishGame = (TextView) gameInfoFinish.findViewById(R.id.bestNumberKill);
		if (bestRankView == null) {
			bestRankView = new RankView("", 0L, 0);
		}
		
		if (bestRankView != null) {
			bestScoreWhenFinishGame.setText(String.valueOf(bestRankView.getScore()));
			bestNumberKillWhenFinishGame.setText(String.valueOf(bestRankView.getNumberKill()));	
		}
		
		comboCounter = new TimeCounter(TimerCombo);
		comboCounter.start();
		hitComboCount = 0;
//		rankViewDAO.getWriteable();
//		rankViewDAO.delete();
//		rankViewDAO.closeConnection();
		
		// Add Score
		fontScoreTexture = new Texture(512, 512, TextureOptions.BILINEAR);
		txtFontScore = new Font(fontScoreTexture, Typeface.create(Typeface.MONOSPACE, Typeface.BOLD_ITALIC), 20, true, Color.RED);
		
		fontComboKillTexture = new Texture(256, 256, TextureOptions.BILINEAR);
		txtFontComboKill = new Font(fontComboKillTexture, Typeface.create(Typeface.MONOSPACE, Typeface.BOLD_ITALIC), 15, true, Color.RED);
		mEngine.getTextureManager().loadTextures(fontScoreTexture, fontComboKillTexture);
		mEngine.getFontManager().loadFonts(txtFontScore, txtFontComboKill);
		
		monsterKilledTexture = new Texture(128, 32, TextureOptions.DEFAULT);
		monsterKilledRegion = TextureRegionFactory.createTiledFromAsset(monsterKilledTexture, this, "icon_monsterKilled_WhenPlaying.png", 0, 0, 3, 1);
		mEngine.getTextureManager().loadTexture(monsterKilledTexture);
		// End add score
	}
	
	public void writePre(){
		SharedPreferences.Editor editor = pre.edit();
		editor.putString("userName", playerNameWhenFinishGame.getText().toString()); 
		editor.commit();
	}
	
	public void saveRank(String playerName){
		if (playerName != null) {
			if (playerName.trim().equals("")) {
				playerName = "Anonymous";
			}
		}else {
			playerName = "Anonymous";
		}
		RankView rankView = new RankView(playerName, hitScore, hitCount);
		rankViewDAO.getWriteable();
		rankViewDAO.insert(rankView);
		rankViewDAO.closeConnection();
		writePre();
	}
	
	private void saveScore(){
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Call Show Dialog
//				STATUS_GAME_CURRENT = false;
				MainGame.this.showDialog(0);
				
			}
			
		});
		
	}
	
	private void pauseGameWhenPlaying(){
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				// TODO Call Show Dialog
//				STATUS_GAME_CURRENT = false;
				MainGame.this.showDialog(1);
				
			}
			
		});
		
	}
	
	public void restart(){
		
		hitCount = 0;
		hitComboCount = 0;
		scoreDurationCombo.setText(String.valueOf(hitComboCount));
		scoreDurationCombo.setVisible(false);
		score.setText(String.valueOf(hitCount));
		monsterKilledText.setText("x " + hitCount);
	}
	
	final protected Dialog onCreateDialog(int id) { 
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		switch (id) {
		case 0:
//			if (hitScore > bestRankView.getScore()) {
//				ImageView crown = (ImageView) gameInfoFinish.findViewById(R.id.crown);
//				crown.setVisibility(View.VISIBLE);
//			}else {
//				ImageView crown = (ImageView) gameInfoFinish.findViewById(R.id.crown);
//				crown.setVisibility(View.INVISIBLE);
//			}
			currentScoreWhenFinishGame.setText(String.valueOf(hitScore));
			currentNumberKillWhenFinishGame.setText(String.valueOf(hitCount));
			
			if (bestRankView != null) {
				if (hitScore > bestRankView.getScore()) {
					builder.setIcon(R.drawable.crown);
				}
			}
			
			builder
			.setTitle("GAME OVER")
			.setPositiveButton("TRY AGAIN", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					saveRank(playerNameWhenFinishGame.getText().toString());
//					Toast.makeText(getBaseContext(),
//							"Score saved", Toast.LENGTH_SHORT).show();
					finish();
					startActivity(new Intent(getBaseContext(), MainGame.class));
				}
			})
			.setNeutralButton("CHARACTERS", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					saveRank(playerNameWhenFinishGame.getText().toString());
					finish();
					startActivity(new Intent(getBaseContext(), ChoseCharacterAndMapActivity.class));
				}
			})
			.setNegativeButton("MENU", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					saveRank(playerNameWhenFinishGame.getText().toString());
					finish();
					startActivity(new Intent(getBaseContext(), MainMenu.class));
				}
			})
			.setView(gameInfoFinish);
			
			break;
		case 1 : 
			currentScoreWhenPauseGame.setText(String.valueOf(hitScore));
			currentNumberKillWhenPauseGame.setText(String.valueOf(hitCount));
			
			builder
			.setTitle("PAUSE GAME")
			.setPositiveButton("CONTINUE", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					pauseGame();
				}
			})
			.setNeutralButton("CHARACTERS", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					finish();
					startActivity(new Intent(getBaseContext(), ChoseCharacterAndMapActivity.class));
				}
			})
			.setNegativeButton("MENU", new
					DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog,
						int whichButton)
				{
					finish();
					startActivity(new Intent(getBaseContext(), MainMenu.class));
				}
			})
			.setView(gameInfoWhenPauseGame);
			
		}
			
			
			
			Dialog dialog = builder.create();
			dialog.setCancelable(false); 
			return dialog;
//		}
		
//		return null;
	}
	
	private void preparePauseGame(){
		pauseTexture = new Texture(64, 64, TextureOptions.DEFAULT);
		pauseTextureRegion = TextureRegionFactory.createFromAsset(pauseTexture, this, "Pause1.png", 0, 0);
		
		pauseEffect = new Texture(256, 64, TextureOptions.DEFAULT);
		pauseEffectTextureRegion = TextureRegionFactory.createFromAsset(pauseEffect, this, "paused.png", 0, 0);
		
		mEngine.getTextureManager().loadTextures(pauseTexture, pauseEffect);
		
		// RANK
		pre = getSharedPreferences(Wellcome.PREFS_NAME, Context.MODE_PRIVATE);
		factoryWhenPauseGame = LayoutInflater.from(this);
		gameInfoWhenPauseGame = factoryWhenPauseGame.inflate(R.layout.pause_scene, null);
		
		rankViewDAO = new RankViewDAO(this);
		rankViewDAO.getReadable();
		bestRankView = rankViewDAO.getBestRankView();
		rankViewDAO.closeConnection();
		
		playerNameWhenPauseGame = (TextView) gameInfoWhenPauseGame.findViewById(R.id.playerNameWhenPlaying);
		playerNameWhenPauseGame.setText(pre.getString("userName", ""));
		
		currentScoreWhenPauseGame = (TextView) gameInfoWhenPauseGame.findViewById(R.id.currentScoreWhenPlaying);
		currentNumberKillWhenPauseGame = (TextView) gameInfoWhenPauseGame.findViewById(R.id.currentNumberKillWhenPlaying);
		
		bestScoreWhenPauseGame = (TextView) gameInfoWhenPauseGame.findViewById(R.id.bestScoreWhenPlaying); 
		bestNumberKillWhenPauseGame = (TextView) gameInfoWhenPauseGame.findViewById(R.id.bestNumberKillWhenPlaying);
		if (bestRankView == null) {
			bestRankView = new RankView("", 0L, 0);
		}
		
		if (bestRankView != null) {
			bestScoreWhenPauseGame.setText(String.valueOf(bestRankView.getScore()));
			bestNumberKillWhenPauseGame.setText(String.valueOf(bestRankView.getNumberKill()));	
		}
		
	}
	
	public void onLoadResources() {
		TextureRegionFactory.setAssetBasePath("gfx/");
		
		// PREPARE BASE DATA AND SETTING : 
		// MAP, CHARACTER, SETTING FOR SOUND, MUSIC, ROTATE
		loadBaseDataAndSetting();
		
		// RANK
		prepareToSaveRank();
		
		// ITEM
		prepareItem();
		
		// SOUND
		prepareSound();
		
		// PLAYER
		mPlayerTexture = new Texture(512, 128, TextureOptions.DEFAULT);
		mPlayerTextureRegion = TextureRegionFactory.createTiledFromAsset(
				mPlayerTexture, this, characterPath, 0, 0, 6, 2);
		// when died
		mPlayerDiedTexture = new Texture(512, 128, TextureOptions.DEFAULT);
		mPlayerDiedTextureRegion = TextureRegionFactory.createTiledFromAsset(
				mPlayerDiedTexture, this, characterPathWhenDied, 0, 0, 6, 1);
		
		// ENEMY
		enemyInActiveTexture = new Texture(512, 128, TextureOptions.DEFAULT);
		enemyInactiveTextureRegion = TextureRegionFactory.createTiledFromAsset(
				enemyInActiveTexture, this, "enemyInActive.png", 0, 0, 6, 2);
		
		enemyActiveTexture = new Texture(512, 128, TextureOptions.DEFAULT);
		enemyActiveTextureRegion = TextureRegionFactory.createTiledFromAsset(
				enemyActiveTexture, this, "enemyActive.png", 0, 0, 6, 2);
		// Enemy is Affected
		enemyAffectedTexture = new Texture(512, 64, TextureOptions.DEFAULT);
		enemyAffectedTextureRegion = TextureRegionFactory.createTiledFromAsset(enemyAffectedTexture, this, "Monster_waterball-actack(60x60)_2.png", 0, 0, 8, 1);
		
		// ENEMY DIED
		enemyDied_Water_Texture = new Texture(256, 64, TextureOptions.DEFAULT);
		enemyDied_Water_TextureRegion = TextureRegionFactory.createTiledFromAsset(enemyDied_Water_Texture, this, "enemyDied_Water.png", 0, 0, 3, 1);
		
		enemyDied_Fire_Texture = new Texture(256, 64, TextureOptions.DEFAULT);
		enemyDied_Fire_TextureRegion = TextureRegionFactory.createTiledFromAsset(enemyDied_Fire_Texture, this, "enemyDied_Fire.png", 0, 0, 3, 1);
		
		// BACKGROUND
		bgTexture = new Texture(1024, 1024, TextureOptions.DEFAULT);
		bgTextureRegion = TextureRegionFactory.createFromAsset(bgTexture, this,
				backgroundPath, 0, 0);
		
		mEngine.getTextureManager().loadTextures(bgTexture, mPlayerTexture, enemyInActiveTexture, enemyActiveTexture, mPlayerDiedTexture, enemyAffectedTexture, enemyDied_Water_Texture, enemyDied_Fire_Texture);

		// Pause Scene
		preparePauseGame();
		
		// Time to show dialog
		timeToShowDialog = new TimeCounter(2);
		timeToShowDialog.start();
	}

	private void showDialogEndGame(float pSecondsElapsed){
		if (timeToShowDialog.getTotal() < 0 || !timeToShowDialog.currentStatus()) {
			saveScore();
		}else {
			timeToShowDialog.update(pSecondsElapsed);
		}
	}
	
	private void gameOver(){
		synchronized (mPlayer) {
			mPlayer.setVelocity(0, 0);
			playerWhenDied = new Creature(mPlayer.getX(), mPlayer.getY(), mPlayerDiedTextureRegion);
			scene.detachChild(mPlayer);
			
			playerWhenDied.setZIndex(LAYER_PLAYER);
			scene.attachChild(playerWhenDied);
			playerWhenDied.animate(200, true);
			flag_EndGame = true;
			timeToActiveDialogSaveScore.start();
			return;
		}
	}
	
	// LOAD RESOURCE FOR LINE ENEMY
//	public Creature getEnemy(float x, float y) {
//		Creature enemy = new Creature(x, y, mCreepTextureRegion.clone());
//		enemy.init(0, 2, 3, 5, 0, 2, 3, 5, mCreepAnimationDuration,
//				mCreepAnimationDuration, mCreepAnimationDuration,
//				mCreepAnimationDuration);
//		enemy.setScale(0.4f);
//		return enemy;
//	}
	public Creature getEnemy(float x, float y, int type) {
		Creature enemy;
		if (type == Enemy.ACTIVE) {
			enemy = new Creature(x, y, enemyActiveTextureRegion.clone());
		}else {
			enemy = new Creature(x, y, enemyInactiveTextureRegion.clone());
		}
		
		enemy.init(0, 5, 6, 11, 0, 5, 6, 11, mCreepAnimationDuration,
				mCreepAnimationDuration, mCreepAnimationDuration,
				mCreepAnimationDuration);
		
//		enemy.animate(200);
		
		enemy.timeToChangeTarget = new TimeCounter(1.5f);
		
		
		enemy.setScale(0.5f);
		return enemy;
	}
	
	private void generateEnemy(){
		Enemy enemy = new Enemy();
		enemy.creature = getEnemy(
				(float) (Math.random() * CAMERA_WIDTH),
				(float) (Math.random() * CAMERA_HEIGHT), Enemy.INACTIVE);
		enemy.timeToActive = new TimeCounter(1.2f);
		enemy.creature.setZIndex(LAYER_ENEMY);
		enemy.creature.animate(enemyInActiveAnimationDuration, false);
		arrListInactiveEnemy.add(enemy);
		scene.attachChild(enemy.creature);
		enemy.timeToActive.start();
	}
	
	private float calDistance(float x0, float y0, float x1, float y1){
		return (float)Math.sqrt((x0-x1)*(x0-x1) +(y0-y1)*(y0-y1));
	}
	
	private void getCoefficient(){
		magnitudePlayer = (float)Math.sqrt(mPlayer.getWidthScaled() * mPlayer.getWidthScaled() + mPlayer.getHeightScaled() * mPlayer.getHeightScaled()); 
//				1.8f * (float)Math.sqrt(mPlayer.getWidth() * mPlayer.getWidth() + mPlayer.getHeight() * mPlayer.getHeight());
		//		magnitudePlayer = 2f * (float)Math.sqrt(mPlayer.getWidth() * mPlayer.getWidth() + mPlayer.getHeight() * mPlayer.getHeight());
		Log.w("Manitude Player After Scale", String.valueOf(magnitudePlayer));
		lengLineEnemy = calDistance(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
		float rate = magnitudePlayer / lengLineEnemy; 
		increaseX = rate * CAMERA_WIDTH;
		increaseY = rate * CAMERA_HEIGHT;
	}
	
	private int getCorNumber(){
		int cor = CORDINATE_1;
		synchronized (mPlayer) {
			if (mPlayer.getX() <= CAMERA_WIDTH/2) {
				if (mPlayer.getY() <= CAMERA_HEIGHT/2) {
					cor = CORDINATE_3;
				}else {
					cor = CORDINATE_2;
				}
			}else {
				if (mPlayer.getY() <= CAMERA_HEIGHT/2) {
					cor = CORDINATE_4;
				}else {
					cor = CORDINATE_1;
				}
			}
		}

		return cor;
	}
	
	private void generateLineEnemy(){
//		if (System.currentTimeMillis() - lastTeamEnemy > 15000) {
//			lastTeamEnemy = System.currentTimeMillis();
//			countLineEnemy++;
//			generateLineEnemy(getCorNumber());
			int corNumber = getCorNumber();
		
			float startX = 0, startY = 0, endX = 0, endY = 0;
			float x = startX, y = startY, inx, iny;
			inx = increaseX;
			iny = increaseY;
			switch (corNumber) {
			case 1:
				startX = -CAMERA_WIDTH/2;
				startY = CAMERA_HEIGHT/2;
				endX = CAMERA_WIDTH/2;
				endY = -CAMERA_HEIGHT/2;
				iny = -iny;
				x = startX; y = startY;
				while (x <= endX && y >= endY) {
					Enemy enemy = new Enemy(getEnemy(x, y, Enemy.ACTIVE), corNumber, 1, new Cordinate(x + CAMERA_WIDTH, y + CAMERA_HEIGHT));
					enemy.creature.setZIndex(LAYER_ENEMY);
					arrLineEnemy.add(enemy);
					scene.attachChild(enemy.creature);
					x += inx;
					y += iny;
				}
				break;
			case 2:
				startX = CAMERA_WIDTH/2;
				startY = -CAMERA_HEIGHT/2;
				endX = 3*CAMERA_WIDTH/2;
				endY = CAMERA_HEIGHT/2;
				x = startX; y = startY;
				while (x <= endX && y <= endY) {
					Enemy enemy = new Enemy(getEnemy(x, y, Enemy.ACTIVE), corNumber, 1, new Cordinate(x - CAMERA_WIDTH, y + CAMERA_HEIGHT));
					enemy.creature.setZIndex(LAYER_ENEMY);
					arrLineEnemy.add(enemy);
					scene.attachChild(enemy.creature);
					//				arrCorLineAgainst.add(new Cordinate(x - CAMERA_WIDTH, y + CAMERA_HEIGHT));
					x += inx;
					y += iny;
				}
				break;
			case 3:
				startX = CAMERA_WIDTH/2;
				startY = 3*CAMERA_HEIGHT/2;
				endX = 3*CAMERA_WIDTH/2;
				endY = CAMERA_HEIGHT/2;
				iny = -iny;
				x = startX; y = startY;
				while (x <= endX && y >= endY) {
					Enemy enemy = new Enemy(getEnemy(x, y, Enemy.ACTIVE), corNumber, 1, new Cordinate(x - CAMERA_WIDTH, y - CAMERA_HEIGHT));
					enemy.creature.setZIndex(LAYER_ENEMY);
					arrLineEnemy.add(enemy);
					scene.attachChild(enemy.creature);
					//				arrCorLineAgainst.add(new Cordinate(x - CAMERA_WIDTH, y - CAMERA_HEIGHT));
					x += inx;
					y += iny;
				}
				break;
			case 4:
				startX = -CAMERA_WIDTH/2;
				startY = CAMERA_HEIGHT/2;
				endX = CAMERA_WIDTH/2;
				endY = 3*CAMERA_HEIGHT/2;
				x = startX; y = startY;
				while (x <= endX && y <= endY) {
					Enemy enemy = new Enemy(getEnemy(x, y, Enemy.ACTIVE), corNumber, 1, new Cordinate(x + CAMERA_WIDTH, y - CAMERA_HEIGHT));
					enemy.creature.setZIndex(LAYER_ENEMY);
					arrLineEnemy.add(enemy);
					scene.attachChild(enemy.creature);
					//				arrCorLineAgainst.add(new Cordinate(x + CAMERA_WIDTH, y - CAMERA_HEIGHT));
					x += inx;
					y += iny;
				}
				break;
			}
//		}
	}
	
	private void updateStatusEnemy(float pSecondsElapsed){
		for (int i = arrListInactiveEnemy.size() - 1; i >= 0 ; i--) {
			Enemy enemy = arrListInactiveEnemy.get(i);
			if (enemy.timeToActive.getTotal() <= 0 || !enemy.timeToActive.currentStatus()) {
				synchronized (enemy) {
					scene.detachChild(enemy.creature);
					Creature creature = getEnemy(enemy.creature.getX(), enemy.creature.getY(), Enemy.ACTIVE);
					creature.setZIndex(LAYER_ENEMY);
					arrListInactiveEnemy.remove(i);
					arrListActiveEnemy.add(creature);
					creature.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					creature.timeToChangeTarget.start();
					scene.attachChild(creature);
				}
			}else {
				enemy.timeToActive.update(pSecondsElapsed);
			}
		}
	}
	
	
	private void loadItem(){
//		auxiliaryTimeCounter = new TimeCounter(-1f);
//		auxiliaryEffectTimeCounter = new TimeCounter(10f);
//		crazyPlayer = false;
//		isActiveAuxiliary = false;
		listItemPrepare.add(new Items(Items.AUXILIARY, new AnimatedSprite(0, 0,auxiliaryItemTextureRegion)
						, new AnimatedSprite(0, 0, auxiliaryEffectItemTextureRegion), -1f, 5f));
//		auxiliaryItemSpriteAfterActive = new AnimatedSprite(0, 0, auxiliaryItemEffectAfterActiveTextureRegion);
		
		protectTimeCounter = new TimeCounter(-1f);
		protectEffectTimeCounter = new TimeCounter(10f);
		protectPlayer = false;
		isActiveProtect = false;
		listItemPrepare.add(new Items(Items.PROTECTION,  new AnimatedSprite(0, 0, protectItemTextureRegion).animate(200)
						, new AnimatedSprite(0, 0, protectEffectItemTextureRegion), -1f, 5f));
		
//		listItemPrepare.add(new Items(Items.SMALL_SCALE_DAMAGE,  new AnimatedSprite(0, 0, smallDamageItemTextureRegion).animate(200)
//						, new AnimatedSprite(0, 0, smallDamageEffectItemTextureRegion), -1f, 5f));
		listItemPrepare.add(new Items(Items.SMALL_SCALE_DAMAGE,  new AnimatedSprite(0, 0, smallDamageItemTextureRegion)
				, new AnimatedSprite(0, 0, smallDamageEffectItemTextureRegion), -1f, 3f));
		listItemPrepare.add(new Items(Items.LARGE_SCALE_DAMAGE,  new AnimatedSprite(0, 0, largeDamageItemTextureRegion).animate(200)
		, new AnimatedSprite(0, 0, largeDamageEffectItemTextureRegion).animate(300), 1f, -1f));
		
		itemManager = new ItemManager(listItemPrepare, 4, new Region(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT));
	}
	
	private void loadPauseGame(){
		clickToPauseGame = new Sprite(0, 0, pauseTextureRegion);
		clickToPauseGame.setZIndex(LAYER_BACKGROUND);
		scene.attachChild(clickToPauseGame);
		regionClickToPauseGame = new Region(0, 0, clickToPauseGame.getWidthScaled(), clickToPauseGame.getHeightScaled());
		
	}
	
	private void pauseGame(){
		if (mEngine.isRunning()) {
			mEngine.stop();
		} else {
			mEngine.start();
		}
	}
	
	public Scene onLoadScene() {
		enableAccelerometerSensor(this);
		scene = new Scene(1);
		lastTimeEnemyAppear = System.currentTimeMillis();
		lastTeamEnemy = System.currentTimeMillis();
		
		// LOAD BACKGROUND
		final Sprite bgSprite = new Sprite(0, 0, bgTextureRegion);
		bgSprite.setWidth(CAMERA_WIDTH);
		bgSprite.setHeight(CAMERA_HEIGHT);
		bgSprite.setZIndex(LAYER_BACKGROUND);
		
		scene.attachChild(bgSprite);
		
		// Load Pause Game
		loadPauseGame();
		
		// LOAD ITEM
		loadItem();
		
		// LOAD PLAYER
		mPlayer = new Creature(CAMERA_WIDTH / 2, CAMERA_HEIGHT / 2,
				mPlayerTextureRegion);
		mPlayer.init(0, 5, 6, 11, 0, 5, 6, 11, mPlayerAnimationDuration,
				mPlayerAnimationDuration, mPlayerAnimationDuration,
				mPlayerAnimationDuration);
		mPlayer.animate(200);
//		float sizePlayer = (float)Math.sqrt(mPlayer.getWidth() * mPlayer.getWidth() + mPlayer.getHeight() * mPlayer.getHeight());
//		Log.w("Manitude Player", String.valueOf(sizePlayer));
//		mPlayer.setScale(1.5f);
		mPlayer.setZIndex(LAYER_PLAYER);
		
		scene.attachChild(mPlayer);
		
		// LOAD RESOURCE FOR LINE ENEMY
		getCoefficient();
		
		scene.registerUpdateHandler(new IUpdateHandler() {
			
			public synchronized void onUpdate(float pSecondsElapsed) {
				
				if (flag_EndGame) {
					showDialogEndGame(pSecondsElapsed);
					return;
				}
				
				for (int i = arrListEnemyDied.size()-1; i >= 0 ; i--) {
					Enemy enemy = arrListEnemyDied.get(i);
					if (enemy.timeToDisapear.getTotal() < 0 || !enemy.timeToDisapear.currentStatus()) {
							synchronized (enemy) {
								scene.detachChild(enemy.enemyDied);
								arrListEnemyDied.remove(i);
								continue;
							}
					}else {
						enemy.timeToDisapear.update(pSecondsElapsed);
						continue;
					}
				}
				
				increaseSweep(pSecondsElapsed);
				
				updateStatusEnemy(pSecondsElapsed);
				updateStatusEnemyAffected(pSecondsElapsed);
				
				mPlayer.processOnGround(CAMERA_WIDTH, CAMERA_HEIGHT,
						pSecondsElapsed);
				
//				generateEnemy();
//				generateLineEnemy();
				
				generateItem();
				
				calScoreAfterCombo(pSecondsElapsed);
				
				auxiliaryItemEffect(pSecondsElapsed);
				protectItemEffect(pSecondsElapsed);
				smallDamageItemEffect(pSecondsElapsed);
				largeDamageItemEffect(pSecondsElapsed);
				
				scene.sortLayers();
				mPlayer.update(pSecondsElapsed);
				updateCreeps(pSecondsElapsed);
				updateCreepsLineEnemy(pSecondsElapsed);
				comboCounter.update(pSecondsElapsed);
			}

			public void reset() {

			}
		});
		scene.registerUpdateHandler(enemyTimerHandler);
		scene.registerUpdateHandler(lineEnemyTimerHandler);
		
		scene.setOnSceneTouchListener(new IOnSceneTouchListener() {

			public boolean onSceneTouchEvent(Scene pScene,
					TouchEvent pSceneTouchEvent) {
				if (regionClickToPauseGame.isCovered(new Cordinate(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()), regionClickToPauseGame)) {
					pauseGame();
					pauseGameWhenPlaying();
				}
				
//				float r;
//				float dx = pSceneTouchEvent.getX()-mPlayer.getX();
//				float dy = pSceneTouchEvent.getY()-mPlayer.getY();
//				r = mSpeed/((float) Math.sqrt(dx*dx + dy*dy));
//				mPlayer.setVelocity(dx*r, dy*r);
				return true;
			}
		});

		// Add Score
		score = new ChangeableText(0, 0, txtFontScore, String.valueOf(maxScore));
		score.setPosition(CAMERA_WIDTH - txtFontScore.getStringWidth(String.valueOf(maxScore)), 0);
		score.setZIndex(LAYER_PLAYER);
		scene.attachChild(score);
		
		//Add Score when combo
		scoreDurationCombo = new ChangeableText(0, 0, txtFontComboKill, String.valueOf(maxScore)); 
		
//		scoreDurationCombo.setPosition(CAMERA_WIDTH - score.getWidthScaled() - 5, score.getY() + score.getHeightScaled() + 5);
		scoreDurationCombo.setPosition(CAMERA_WIDTH - txtFontScore.getStringWidth(String.valueOf(maxScore)), score.getY() + score.getHeightScaled());
		scoreDurationCombo.setZIndex(LAYER_PLAYER);
		scene.attachChild(scoreDurationCombo);
		scoreDurationCombo.setVisible(false);
		// End add score when combo
		
		monsterKilledWhenPlaying = new AnimatedSprite(0, 0, monsterKilledRegion);
		monsterKilledWhenPlaying.setPosition(pauseTextureRegion.getWidth() + 10, 0);
		monsterKilledWhenPlaying.setZIndex(LAYER_PLAYER);
		monsterKilledWhenPlaying.animate(200,false);
		scene.attachChild(monsterKilledWhenPlaying);
		monsterKilledText = new ChangeableText(0, 0, txtFontScore, "XXXXXX");
		monsterKilledText.setPosition(monsterKilledWhenPlaying.getX() + monsterKilledWhenPlaying.getWidthScaled(), 0);
		monsterKilledText.setZIndex(LAYER_PLAYER);
		scene.attachChild(monsterKilledText);
		
		restart();
		// End add score
		
		// Background Music
		if (enableBgMusic) {
			bgMusic.play();	
			bgMusic.setLooping(true);
		}
		// End background music
		return scene;
	}

	TimerHandler enemyTimerHandler = new TimerHandler(timeToEnemyAppear, true, new ITimerCallback() {
//		float currentTimeCount = 0f;
		@Override
		public void onTimePassed(TimerHandler pTimerHandler) {
			// TODO Generate Enemy using TimerHandler
//			currentTimeCount += pTimerHandler.getTimerSecondsElapsed();
//			Log.w("Current Time Count", String.valueOf(currentTimeCount));
			generateEnemy();
		}
	});
	
	TimerHandler lineEnemyTimerHandler = new TimerHandler(timeToLineEnemyAppear, true, new ITimerCallback() {
		
		@Override
		public void onTimePassed(TimerHandler pTimerHandler) {
			// TODO Generate Enemy using TimerHandler
			generateLineEnemy();
		}
	});

	private void generateItem(){
		if (itemManager.isNeedMore()) {
			int type;
			int rand = new Random().nextInt(100);
			if (rand <= 10) {
				type = Items.PROTECTION;
			}else if(rand > 10 && rand <= 40) {
				type = Items.AUXILIARY;
			}else if (rand > 40 && rand <= 70) {
				type = Items.SMALL_SCALE_DAMAGE;
			}else {
				type = Items.LARGE_SCALE_DAMAGE;
			}
			
//			type = Items.LARGE_SCALE_DAMAGE;
			
			Items item = itemManager.getItemType(type);
			
			if (item != null){
				if (calcEmptyPosition(item.mInactiveSprite)) {
					itemManager.newItem(item);
					item.mInactiveSprite.setZIndex(LAYER_ITEM);
					item.mInactiveSprite.animate(200);
					scene.attachChild(item.mInactiveSprite);
				}
			}
		}
	}
	
	private void generateSweepLineEnemy(int typeLineWeep){
		float startX = 0, startY = 0, endX = CAMERA_WIDTH, endY = CAMERA_HEIGHT;
		float x = startX, y = startY;
		if (typeLineWeep == 1) {
			while (x <= endX && y <= endY) {
				Enemy enemy = new Enemy();
				enemy.creature = getEnemy(x, y, Enemy.INACTIVE);
				enemy.timeToActive = new TimeCounter(3f);
				enemy.creature.setZIndex(LAYER_ENEMY);
				arrListInactiveEnemy.add(enemy);
				scene.attachChild(enemy.creature);
				enemy.timeToActive.start();
				
				x += increaseX;
				if (x > endX) {
					x = startX;
					y += 2*increaseY;
				}
			}
		}else {
			while (x <= endX && y <= endY) {
				Enemy enemy = new Enemy();
				enemy.creature = getEnemy(x, y, Enemy.INACTIVE);
				enemy.timeToActive = new TimeCounter(3f);
				enemy.creature.setZIndex(LAYER_ENEMY);
				arrListInactiveEnemy.add(enemy);
				scene.attachChild(enemy.creature);
				enemy.timeToActive.start();
				y += increaseY;
				
				if (y > endY) {
					y = startY;
					x += 2*increaseX;
				}
			}
		}
		
	}
	
	private void increaseSweep(float pSecondsElapsed){
		isSweepActive = isSweepByCombo || isSweepByScore;
		
		if (isSweepActive) {
			if (isSweepByCombo) {
				if (reachComboCount == 0) {
					reachComboCount = hitComboCount / reachSweepByCombo;
					reachSweepByCombo *= 2;
					generateSweepLineEnemy(typeSweep);
					enemySpeed = mSpeed * (reachComboCount+0.5f);
					maxEnemyAppearAtTheSameTime *= reachComboCount;
				}else {
					int tempCountReachCombo = hitComboCount / reachSweepByCombo;
					if (tempCountReachCombo > 0) {
						reachComboCount += tempCountReachCombo;
						reachSweepByCombo *= 2;
						increaseSweepTimeCounter.start();
						enemySpeed = mSpeed * (reachComboCount+0.5f);
						maxEnemyAppearAtTheSameTime *= reachComboCount;
					}
				}
				
				if (increaseSweepTimeCounter.currentStatus()) {
//					for (int i = 0; i < maxEnemyAppearAtTheSameTime; i++) {
//						generateEnemy();
//					}
					float timeToEnemyAppearWhenSweep = timeToEnemyAppear / maxEnemyAppearAtTheSameTime;
					enemyTimerHandler.setTimerSeconds(timeToEnemyAppearWhenSweep);
				}else {
					enemyTimerHandler.setTimerSeconds(timeToEnemyAppear);
				}
				isSweepByCombo = increaseSweepTimeCounter.update(pSecondsElapsed);
			}else {
				if (increaseSweepTimeCounter.currentStatus()) {
					reachComboCount = 0;
					enemySpeed = mSpeed;
					reachSweepByCombo = 50;
					maxEnemyAppearAtTheSameTime = 5;
				}
			}
		}else {
			if (increaseSweepTimeCounter.currentStatus()) {
				reachComboCount = 0;
				enemySpeed = mSpeed;
				reachSweepByCombo = 50;
				maxEnemyAppearAtTheSameTime = 5;
			}
		}
	}
	
	private void calScoreWithCombo(float pSecondsElapsed){
		if (comboCounter.currentStatus()) {
			comboCounter.start();
			hitComboCount++;
		}else {
			hitComboCount = 0;
			comboCounter.start();
			hitComboCount++;
		}
		if (hitComboCount >= reachSweepByCombo) {
			isSweepByCombo = true;
			increaseSweepTimeCounter.start();
			typeSweep = new Random().nextInt(2);
		}
		long scorePerKilled = hitComboCount * scorePerEnemyKilled;
		scoreDurationCombo.setText(String.valueOf(scorePerKilled) +"X"+ String.valueOf(hitComboCount));
		scoreDurationCombo.setVisible(true);
	}
	
	private void calScoreAfterCombo(float pSecondsElapsed){
		if (comboCounter.currentStatus()) {
			return;
		}else {
			scoreDurationCombo.setVisible(false);
//			scene.detachChild(scoreDurationCombo);
			hitCount += hitComboCount;
			hitScore += hitComboCount * hitComboCount * scorePerEnemyKilled;
			score.setText(String.valueOf(hitScore));
			hitComboCount = 0;
		}
		monsterKilledWhenPlaying.animate(200,false);
		monsterKilledText.setText("x " + hitCount);
	}
	
	private void updateStatusEnemyAffected(float pSecondsElapsed){
		for (int i = arrListEnemyAffected.size() - 1; i >= 0; i--) {
			Enemy enemy = arrListEnemyAffected.get(i);
			
			if (enemy.isDied) {
				if (enemy.timeToDisapear.getTotal() < 0 || !enemy.timeToDisapear.currentStatus()) {
					synchronized (enemy) {
						scene.detachChild(enemy.enemyDied);
						arrListEnemyAffected.remove(i);
						continue;
					}
				}else {
					enemy.timeToDisapear.update(pSecondsElapsed);
					continue;
				}
			}
			
			if (enemy.creature.checkCollision(mPlayer, pSecondsElapsed)) {
				synchronized (enemy) {
					scene.detachChild(enemy.enemyIsAffected);
					scene.detachChild(enemy.creature);
//					arrListEnemyAffected.remove(i);
					scene.attachChild(enemy.enemyDied);
					enemy.enemyDied.animate(200, false);
					enemy.timeToDisapear.update(pSecondsElapsed);
					enemy.isDied = true;
				}
				calScoreWithCombo(pSecondsElapsed);
				continue;
			}
			
			if (enemy.timeAffected.currentStatus()) {
				enemy.timeAffected.update(pSecondsElapsed);
				continue;
			}
			synchronized (enemy) {
				enemy.creature.setPosition(enemy.enemyIsAffected.getX(), enemy.enemyIsAffected.getY());
				scene.detachChild(enemy.enemyIsAffected);
				scene.attachChild(enemy.creature);
//				enemy.creature.setVisible(true);
//				Creature creature = getEnemy(enemy.creature.getX(), enemy.creature.getY(), Enemy.ACTIVE);
//				creature.setZIndex(LAYER_ENEMY);
				arrListEnemyAffected.remove(i);
				enemy.creature.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
				enemy.creature.timeToChangeTarget.start();
				arrListActiveEnemy.add(enemy.creature);
//				scene.attachChild(enemy.creature);
			}
		}
	}
	
	private boolean isAffected(Creature creature, Region region){
		if (region.isCovered(new Cordinate(creature.getX(), creature.getY()), region)) {
			return true;
		}
		if (region.isCovered(new Cordinate(creature.getX()+creature.getWidthScaled(), creature.getY()), region)) {
			return true;
		}
		if (region.isCovered(new Cordinate(creature.getX()+creature.getWidthScaled(), creature.getY() + creature.getHeightScaled()), region)) {
			return true;
		}
		
		if (region.isCovered(new Cordinate(creature.getX(), creature.getY() + creature.getHeightScaled()), region)) {
			return true;
		}
		return  false;
	}
	
	private void auxiliaryItemEffectAfterActive(Creature creature, float pTimeAffect){
		Enemy enemy = new Enemy();
		enemy.creature = getEnemy(creature.getX(), creature.getY(), Enemy.ACTIVE);
		enemy.creature.setZIndex(LAYER_ENEMY);
		scene.detachChild(creature);
		enemy.timeAffected = new TimeCounter(pTimeAffect);
		
		AnimatedSprite enemyIsAffected = new AnimatedSprite(0, 0, enemyAffectedTextureRegion.clone());
		enemyIsAffected.setScale(0.5f);
		enemyIsAffected.animate(enemyIsEffectedAnimationDuration, 0, 7, false);
		enemyIsAffected.setZIndex(LAYER_ENEMY);
		enemyIsAffected.setPosition(enemy.creature.getX() + (enemy.creature.getWidth()-enemyIsAffected.getWidth())/2, enemy.creature.getY() + (enemy.creature.getHeight()-enemyIsAffected.getHeight())/2);
		
		enemy.enemyDied = new AnimatedSprite(0, 0, enemyDied_Water_TextureRegion.clone());
		enemy.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
		enemy.enemyDied.setZIndex(LAYER_ENEMY);
		enemy.enemyDied.animate(200,false);
		enemy.timeToDisapear.start();
		
		enemy.enemyIsAffected = enemyIsAffected;
		arrListEnemyAffected.add(enemy);
//		enemy.creature.setVisible(false);
		scene.attachChild(enemy.enemyIsAffected);
	}
	
	private void auxiliaryItemEffect(float pSecondsElapsed){
		for (int i = arrListAuxiliaryItemActive.size()-1; i >= 0; i--) {
			ItemActive itemActive = arrListAuxiliaryItemActive.get(i);
			if (itemActive.isItemActive) {
				if (itemActive.active) {
//					Log.w("Loop count ", "" + itemActive.countLoop);
					if (itemActive.item.getCurrentTileIndex() == 2) {
						createAnimationFromI2JByCountLoop(itemActive.item, auxiliaryEffectAnimationDuration, 3, 5, 8);
					}
					
					if (itemActive.item.getCurrentTileIndex() == 5) {
						if (itemActive.countLoop < 8) {
							itemActive.countLoop++;	
						}else {
							createAnimationFromI2JByActiveLoop(itemActive.item, auxiliaryEffectAnimationDuration, 6, 9, false);
						}
					}
					
					if (itemActive.timeExistEffectCounter.currentStatus()) {
						itemActive.item.setVisible(true);	
						itemActive.timeExistEffectCounter.update(pSecondsElapsed);
					}else {
						itemActive.item.setVisible(false);
					}
					
					for (int k = arrListInactiveEnemy.size()-1; k >= 0 ; k--) {
						Enemy enemy = arrListInactiveEnemy.get(k);
//						if (isAffected(enemy.creature, itemActive.regionAffect)) {
//						if(itemActive.item.collidesWith(enemy.creature)){
						
						if (isAffected(enemy.creature, itemActive.regionAffect)) {	
//							itemActive.item.collidesWith(enemy.creature)
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListInactiveEnemy.remove(k);
//								scene.detachChild(enemy.creature);
								auxiliaryItemEffectAfterActive(enemy.creature, itemActive.timeActiveCounter.getTotal());
							}
							// Increase score when hit enemy by item
//							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrListActiveEnemy.size()-1; k >= 0; k--) {
						Creature enemy = arrListActiveEnemy.get(k);
						if (isAffected(enemy, itemActive.regionAffect)) {
//						if (itemActive.item.collidesWith(enemy)) {							
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListActiveEnemy.remove(k);
								auxiliaryItemEffectAfterActive(enemy, itemActive.timeActiveCounter.getTotal());
							}
							// Increase score when hit enemy by item
//							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrLineEnemy.size()-1; k >= 0; k--) {
						Enemy enemy = arrLineEnemy.get(k);
//						if (isAffected(enemy.creature, itemActive.regionAffect)) {
						if (isAffected(enemy.creature, itemActive.regionAffect)) {							
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrLineEnemy.remove(k);
								auxiliaryItemEffectAfterActive(enemy.creature, itemActive.timeActiveCounter.getTotal());
							}
							// Increase score when hit enemy by item
//							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					itemActive.active = itemActive.timeActiveCounter.update(pSecondsElapsed);
					itemActive.isItemActive = itemActive.active;
				}else {
					itemActive.item.setVisible(false);
					itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);
				}
			}else {
				if (itemActive.item != null) {
					synchronized (itemActive) {
						scene.detachChild(itemActive.item);
						arrListAuxiliaryItemActive.remove(i);
					}
				}
			}

		}

		Items item = itemManager.getCollisionItem(mPlayer, false);
		if (item != null && item.typeItem == Items.AUXILIARY) {
			ItemActive itemActive = new ItemActive();
			
//			synchronized (mPlayer) {
//				itemActive.regionAffect = new Region(magnitudePlayer, new Cordinate(mPlayer.getX() + mPlayer.getWidthScaled()/2, mPlayer.getY() + mPlayer.getHeightScaled()/2));
//			}
			
			itemActive.countLoop = 0;
			item.mIsActive = true;
			itemActive.item = item.mActiveSprite;
			itemActive.cordinateActive = new Cordinate(item.mInactiveSprite.getX() + (item.mInactiveSprite.getWidthScaled()-itemActive.item.getWidthScaled())/2, item.mInactiveSprite.getY() + (item.mInactiveSprite.getHeightScaled() - itemActive.item.getHeightScaled())/2);
			itemActive.item.setPosition(itemActive.cordinateActive.x, itemActive.cordinateActive.y);
//			itemActive.item.setPosition(item.mInactiveSprite.getX() + (item.mInactiveSprite.getWidthScaled()-itemActive.item.getWidthScaled())/2, item.mInactiveSprite.getY() + (item.mInactiveSprite.getHeightScaled() - itemActive.item.getHeightScaled())/2);
			
			itemActive.regionAffect = new Region( (float)(Math.sqrt((itemActive.item.getWidthScaled()*itemActive.item.getWidthScaled() + itemActive.item.getHeightScaled()*itemActive.item.getHeightScaled()))/2), new Cordinate(itemActive.cordinateActive.x + itemActive.item.getWidthScaled()/2, itemActive.cordinateActive.y + itemActive.item.getHeightScaled()));
			
			itemManager.removeItem(item);
			scene.detachChild(item.mInactiveSprite);
			
			itemActive.timeToActiveCounter = new TimeCounter(item.mTimeToActiveCounter.getTotal());
			itemActive.timeExistEffectCounter = new TimeCounter(item.mActiveTimeCounter.getTotal()/2);
			itemActive.timeActiveCounter = new TimeCounter(item.mActiveTimeCounter.getTotal());
			
			itemActive.isItemActive = true;
			
			
			if (itemActive.item != null) {
				 
				itemActive.item.setZIndex(LAYER_BACKGROUND);
				createAnimationFromI2JByActiveLoop(itemActive.item, auxiliaryEffectAnimationDuration, 0, 2, false);
				
				scene.attachChild(itemActive.item);
				
				itemActive.item.setVisible(false);
				arrListAuxiliaryItemActive.add(itemActive);
			}
			itemActive.timeToActiveCounter.start();
			if (itemActive.timeToActiveCounter.getTotal() < 0) {
				itemActive.active = true;
			}else {
				itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);	
			}
			
			if (itemActive.active) {
				itemActive.timeActiveCounter.start();
				if (itemActive.item != null) {
					itemActive.item.setVisible(true);
				}
			}
		}
	}
	
	private void protectItemEffect(float pSecondsElapsed){
		if (isActiveProtect) {
			if (protectPlayer) {
				for (int i = arrListInactiveEnemy.size()-1; i >= 0; i--) {
					Enemy enemy = arrListInactiveEnemy.get(i);
					if (protectItemActive.collidesWith(enemy.creature)) {
						// Effect when collision
						effectWhenCollision();
						// End effect when collision
						
						synchronized (enemy) {
							arrListInactiveEnemy.remove(i);
							
							Enemy enemyDied = new Enemy();
							enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
							enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
							enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
							enemyDied.enemyDied.animate(200,false);
							enemyDied.timeToDisapear.start();
							enemyDied.isDied = true;
							scene.attachChild(enemyDied.enemyDied);
							arrListEnemyDied.add(enemyDied);
							
							scene.detachChild(enemy.creature);
						}
						// Increase score when hit enemy by item
//						hitCount ++;
//						hitScore += 7;
//						score.setText(String.valueOf(hitScore));
						calScoreWithCombo(pSecondsElapsed);
						// End Increase score when hit enemy by item
					}
				}
				
				for (int i = arrListActiveEnemy.size()-1; i >= 0; i--) {
					Creature enemy = arrListActiveEnemy.get(i);
					if (protectItemActive.collidesWith(enemy)) {
						// Effect when collision
						effectWhenCollision();
						// End effect when collision
						
						synchronized (enemy) {
							arrListActiveEnemy.remove(i);
							
							Enemy enemyDied = new Enemy();
							enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
							enemyDied.enemyDied.setPosition(enemy.getX(), enemy.getY());
							enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
							enemyDied.enemyDied.animate(200,false);
							enemyDied.timeToDisapear.start();
							enemyDied.isDied = true;
							scene.attachChild(enemyDied.enemyDied);
							arrListEnemyDied.add(enemyDied);
							
							scene.detachChild(enemy);
						}
						// Increase score when hit enemy by item
//						hitCount ++;
//						hitScore += 7;
//						score.setText(String.valueOf(hitScore));
						calScoreWithCombo(pSecondsElapsed);
						// End Increase score when hit enemy by item
					}
				}
				
				for (int i = arrLineEnemy.size()-1; i >= 0; i--) {
					Enemy enemy = arrLineEnemy.get(i);
					if (protectItemActive.collidesWith(enemy.creature)) {
						// Effect when collision
						effectWhenCollision();
						// End effect when collision
						
						synchronized (enemy) {
							arrLineEnemy.remove(i);
							
							Enemy enemyDied = new Enemy();
							enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
							enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
							enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
							enemyDied.enemyDied.animate(200,false);
							enemyDied.timeToDisapear.start();
							enemyDied.isDied = true;
							scene.attachChild(enemyDied.enemyDied);
							arrListEnemyDied.add(enemyDied);
							
							scene.detachChild(enemy.creature);
						}
						// Increase score when hit enemy by item
//						hitCount ++;
//						hitScore += 7;
//						score.setText(String.valueOf(hitScore));
						calScoreWithCombo(pSecondsElapsed);
						// End Increase score when hit enemy by item
					}
				}
				
				for (int i = arrListEnemyAffected.size()-1; i >= 0; i--) {
					Enemy enemy = arrListEnemyAffected.get(i);
					if (protectItemActive.collidesWith(enemy.creature)) {
						// Effect when collision
						effectWhenCollision();
						// End effect when collision
						
						synchronized (enemy) {
							arrListEnemyAffected.remove(i);
							
							Enemy enemyDied = new Enemy();
							enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
							enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
							enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
							enemyDied.enemyDied.animate(200,false);
							enemyDied.timeToDisapear.start();
							enemyDied.isDied = true;
							scene.attachChild(enemyDied.enemyDied);
							arrListEnemyDied.add(enemyDied);
							
							scene.detachChild(enemy.creature);
							scene.detachChild(enemy.enemyIsAffected);
						}
						// Increase score when hit enemy by item
						calScoreWithCombo(pSecondsElapsed);
						// End Increase score when hit enemy by item
					}
				}
				
				protectPlayer = protectEffectTimeCounter.update(pSecondsElapsed);
				isActiveProtect = protectPlayer;
			}else {
				protectPlayer = protectTimeCounter.update(pSecondsElapsed);
			}
		}else {
			if (protectItemActive != null) {
				scene.detachChild(protectItemActive);
			}
		}

		if (protectPlayer) {
			protectItemActive.setPosition(mPlayer.getX() + (mPlayer.getWidth()-protectItemActive.getWidth())/2, mPlayer.getY() + (mPlayer.getHeight()-protectItemActive.getHeight())/2);
			protectItemActive.setVisible(true);
		}else {
			if (protectItemActive != null) {
				protectItemActive.setVisible(false);	
			}
		}

		Items protect_Item = itemManager.getCollisionItem(mPlayer, false);
		if (protect_Item != null && protect_Item.typeItem == Items.PROTECTION) {
			protect_Item.mIsActive = true;
			itemManager.removeItem(protect_Item);
			scene.detachChild(protect_Item.mInactiveSprite);
			if (protectPlayer) {
				protectEffectTimeCounter.start();
				protectPlayer = protectEffectTimeCounter.update(pSecondsElapsed);
				isActiveProtect = protectPlayer;
				return;
			}
			protectTimeCounter.start();
			isActiveProtect = true;
			protectItemActive = protect_Item.mActiveSprite;
			protectItemActive.setVisible(false);
			
			protectPlayer = protectTimeCounter.update(pSecondsElapsed);
			if (protectPlayer) {
				protectEffectTimeCounter.start();
				protectItemActive.setZIndex(LAYER_ITEM_PROTECT);
				scene.attachChild(protectItemActive);
				protectItemActive.setPosition(mPlayer.getX() + (mPlayer.getWidth()-protectItemActive.getWidth())/2, mPlayer.getY() + (mPlayer.getHeight()-protectItemActive.getHeight())/2);
				protectItemActive.setVisible(true);
				protectItemActive.animate(200);
			}
		}
	}
	
	private void smallDamageItemEffect(float pSecondsElapsed){
		Items item = itemManager.getCollisionItem(mPlayer, false);
		if (item != null && item.typeItem == Items.SMALL_SCALE_DAMAGE) {
			item.mIsActive = true;
			itemManager.removeItem(item);
			
			ItemActive itemActive = new ItemActive();
			itemActive.timeToActiveCounter = new TimeCounter(item.mTimeToActiveCounter.getTotal());
			itemActive.timeActiveCounter = new TimeCounter(item.mActiveTimeCounter.getTotal());
			itemActive.item = item.mActiveSprite;
			itemActive.cordinateActive = new Cordinate(item.mInactiveSprite.getX() + (item.mInactiveSprite.getWidthScaled()-itemActive.item.getWidthScaled())/2, item.mInactiveSprite.getY() + (item.mInactiveSprite.getHeightScaled() - itemActive.item.getHeightScaled())/2);
			scene.detachChild(item.mInactiveSprite);
			
			itemActive.isItemActive = true;
			itemActive.wasActive = false;
			
			if (itemActive.item != null) {
//				itemActive.cordinateActive = new Cordinate(mPlayer.getX() + (mPlayer.getWidthScaled()-itemActive.item.getWidthScaled())/2, mPlayer.getY() + (mPlayer.getHeightScaled()-itemActive.item.getHeightScaled())/2);
//				itemActive.cordinateActive = new Cordinate(mPlayer.getX() + mPlayer.getWidthScaled()/2, mPlayer.getY() + 3*mPlayer.getHeightScaled()/4);
				
				itemActive.item.setZIndex(LAYER_ITEM);
				
				itemActive.item.animate(smallItemEffectAnimationDuration, false);
				itemActive.item.setCurrentTileIndex(0);
				scene.attachChild(itemActive.item);
				itemActive.item.setPosition(itemActive.cordinateActive.x, itemActive.cordinateActive.y);
				itemActive.item.setVisible(false);
				itemActive.regionAffect = new Region( (float)(Math.sqrt((itemActive.item.getWidthScaled()*itemActive.item.getWidthScaled() + itemActive.item.getHeightScaled()*itemActive.item.getHeightScaled()))/2), new Cordinate(itemActive.cordinateActive.x + itemActive.item.getWidthScaled()/2, itemActive.cordinateActive.y + 3*itemActive.item.getHeightScaled()/4));
			}
			itemActive.timeToActiveCounter.start();
			arrListSmallDamageItemActive.add(itemActive);
			
			if (itemActive.timeToActiveCounter.getTotal() < 0) {
				itemActive.active = true;
			}else {
				itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);	
			}
			
			if (itemActive.active) {
				itemActive.timeActiveCounter.start();
				if (itemActive.item != null) {
					itemActive.item.setVisible(true);
				}
			}
		}
		
		for (int i = arrListSmallDamageItemActive.size()-1; i >= 0 ; i--) {
			ItemActive itemActive = arrListSmallDamageItemActive.get(i);
			if (itemActive.isItemActive) {
				if (itemActive.active) {
					if (!itemActive.wasActive) {
						itemActive.item.setVisible(true);
					}
					if (itemActive.item.getCurrentTileIndex() == 8) {
						itemActive.item.stopAnimation();
						itemActive.item.setVisible(false);
						itemActive.wasActive = true;
					}
					
					for (int k = arrListEnemyAffected.size()-1; k >= 0; k--) {
						Enemy enemy = arrListEnemyAffected.get(k);
//						if (itemActive.item.collidesWith(enemy.creature)) {
						if (isAffected(enemy.creature, itemActive.regionAffect)) {	
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListEnemyAffected.remove(k);
								scene.detachChild(enemy.creature);
								scene.detachChild(enemy.enemyIsAffected);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
							}
							// Increase score when hit enemy by item
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrListInactiveEnemy.size()-1; k >= 0 ; k--) {
						Enemy enemy = arrListInactiveEnemy.get(k);
//						if (itemActive.item.collidesWith(enemy.creature)) {
						if (isAffected(enemy.creature, itemActive.regionAffect)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListInactiveEnemy.remove(k);
								scene.detachChild(enemy.creature);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrListActiveEnemy.size()-1; k >= 0; k--) {
						Creature enemy = arrListActiveEnemy.get(k);
//						if (itemActive.item.collidesWith(enemy)) {
						if (isAffected(enemy, itemActive.regionAffect)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListActiveEnemy.remove(k);
								scene.detachChild(enemy);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.getX(), enemy.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrLineEnemy.size()-1; k >= 0; k--) {
						Enemy enemy = arrLineEnemy.get(k);
//						if (itemActive.item.collidesWith(enemy.creature)) {
						if (isAffected(enemy.creature, itemActive.regionAffect)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrLineEnemy.remove(k);
								scene.detachChild(enemy.creature);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					itemActive.active = itemActive.timeActiveCounter.update(pSecondsElapsed);
					itemActive.isItemActive = itemActive.active;
				}else {
					itemActive.item.setVisible(false);
					itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);
				}
				itemActive.item.setCurrentTileIndex(itemActive.item.getCurrentTileIndex());
				arrListSmallDamageItemActive.set(i, itemActive);
			}else {
				if (itemActive.item != null) {
					synchronized (itemActive) {
						scene.detachChild(itemActive.item);
						arrListSmallDamageItemActive.remove(i);
					}
				}
			}

			if (itemActive.active) {
				if (!itemActive.wasActive) {
					itemActive.item.setVisible(true);
				}else {
					itemActive.item.setVisible(false);
				}
			}else {
				if (itemActive.item != null) {
					itemActive.item.setVisible(false);	
				}
			}
			
		}
	}
	
	private void largeDamageItemEffect(float pSecondsElapsed){
		boolean isActive;
		
		for (int i = arrListLargeDamageItemActive.size()-1; i >= 0; i--) {
			ItemActive itemActive = arrListLargeDamageItemActive.get(i);
			if (itemActive.isItemActive) {
				isActive = itemActive.active;
				
				if (itemActive.active) {
					if (itemActive.item.getCurrentTileIndex() == (int)(itemActive.rotate_[0] + 7)) {
						createAnimationFromI2JByActiveLoop(itemActive.item, largeItemEffectAnimationDuration, (int)(itemActive.rotate_[0] + 8), (int)(itemActive.rotate_[1]), true);
						Vector2 vItem = itemActive.velocity;
						
						itemActive.velocity = new Vector2((float)(vItem.x * 1.5), (float)(vItem.y * 1.5));
					}
					itemActive.item.setRotation(itemActive.rotate_[2]);
					scene.detachChild(itemActive.itemPrepareActive);
					itemActive.item.setVisible(true);
					if (itemActive.item.getX() >= CAMERA_WIDTH 
							|| itemActive.item.getX() + itemActive.item.getWidth() <= 0
							|| itemActive.item.getY() >= CAMERA_HEIGHT
							|| itemActive.item.getY() + itemActive.item.getHeight() <= 0) {
						
						synchronized (itemActive) {
							arrListLargeDamageItemActive.remove(i);
							scene.detachChild(itemActive.item);
							continue;
						}
					}
					
					itemActive.update(pSecondsElapsed);
					
					for (int k = arrListEnemyAffected.size()-1; k >= 0; k--) {
						Enemy enemy = arrListEnemyAffected.get(k);
						if (itemActive.item.collidesWith(enemy.creature)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListEnemyAffected.remove(k);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
								
								scene.detachChild(enemy.creature);
								scene.detachChild(enemy.enemyIsAffected);
							}
							// Increase score when hit enemy by item
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrListInactiveEnemy.size()-1; k >= 0; k--) {
						Enemy enemy = arrListInactiveEnemy.get(k);
						if (itemActive.item.collidesWith(enemy.creature)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListInactiveEnemy.remove(k);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
								
								scene.detachChild(enemy.creature);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrListActiveEnemy.size()-1; k >= 0 ; k--) {
						Creature enemy = arrListActiveEnemy.get(k);
						if (itemActive.item.collidesWith(enemy)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrListActiveEnemy.remove(k);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.getX(), enemy.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
								
								scene.detachChild(enemy);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					for (int k = arrLineEnemy.size()-1; k >= 0; k--) {
						Enemy enemy = arrLineEnemy.get(k);
						if (itemActive.item.collidesWith(enemy.creature)) {
							// Effect when collision
							effectWhenCollision();
							// End effect when collision
							
							synchronized (enemy) {
								arrLineEnemy.remove(k);
								
								Enemy enemyDied = new Enemy();
								enemyDied.enemyDied = new AnimatedSprite(0, 0, enemyDied_Fire_TextureRegion.clone());
								enemyDied.enemyDied.setPosition(enemy.creature.getX(), enemy.creature.getY());
								enemyDied.enemyDied.setZIndex(LAYER_ENEMY);
								enemyDied.enemyDied.animate(200,false);
								enemyDied.timeToDisapear.start();
								enemyDied.isDied = true;
								scene.attachChild(enemyDied.enemyDied);
								arrListEnemyDied.add(enemyDied);
								
								scene.detachChild(enemy.creature);
							}
							// Increase score when hit enemy by item
//							hitCount ++;
//							hitScore += 7;
//							score.setText(String.valueOf(hitScore));
							calScoreWithCombo(pSecondsElapsed);
							// End Increase score when hit enemy by item
						}
					}
					
					itemActive.active = itemActive.timeActiveCounter.update(pSecondsElapsed);
					itemActive.isItemActive = itemActive.active;
				}else {
					setPositionItem(mPlayer, itemActive.itemPrepareActive);
					
					itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);
				}
				
				if (!isActive && itemActive.active) {
					setPositionItem(mPlayer, itemActive.item);
					itemActive.timeActiveCounter.start();
					scene.detachChild(itemActive.itemPrepareActive);
					itemActive.item.setVisible(true);
					synchronized (mPlayer) {
						itemActive.rotate_ = mPlayer.getAngle();
						itemActive.item.setCurrentTileIndex((int)itemActive.rotate_[0]);
						createAnimationFromI2JByActiveLoop(itemActive.item, largeItemEffectAnimationDuration, (int)itemActive.rotate_[0], (int)(itemActive.rotate_[0]+7), false);
						
						itemActive.item.setRotation(itemActive.rotate_[2]);
					}
					
					if (itemActive.item != null) {
						float v0 = (float) Math.sqrt(mPlayer.getVelocity().x * mPlayer.getVelocity().x + mPlayer.getVelocity().y * mPlayer.getVelocity().y);
						float rateX = mPlayer.getVelocity().x / v0;
						float rateY = mPlayer.getVelocity().y / v0;
						itemActive.velocity = new Vector2();
						itemActive.velocity.x = 4 * rateX * mSpeed;
						itemActive.velocity.y = 4 * rateY * mSpeed;
//						itemActive.item.animate(300);
						itemActive.update(pSecondsElapsed);
						
					}
				}
//				else {
//					if (itemActive.item != null) {
//						itemActive.item.setVisible(false);	
//					}
//				}
				
			}
//			else {
//				if (itemActive.item != null) {
//					synchronized (itemActive) {
//						scene.detachChild(itemActive.item);
//						arrListLargeDamageItemActive.remove(i);
//					}
//				}
//			}

		}

		Items item = itemManager.getCollisionItem(mPlayer, false);
		if (item != null && item.typeItem == Items.LARGE_SCALE_DAMAGE) {
			
			item.mIsActive = true;
			itemManager.removeItem(item);
			
//			scene.detachChild(item.mInactiveSprite);
			
			ItemActive itemActive = new ItemActive();
			itemActive.itemPrepareActive = item.mInactiveSprite;
//			itemActive.itemPrepareActive.setScale(2f);
			itemActive.itemPrepareActive.setZIndex(LAYER_ITEM_PROTECT);
//			itemActive.itemPrepareActive.setPosition(mPlayer.getX() + (mPlayer.getWidth()-itemActive.itemPrepareActive.getWidth())/2, mPlayer.getY() + (mPlayer.getHeight()-itemActive.itemPrepareActive.getHeight())/2);
			setPositionItem(mPlayer, itemActive.itemPrepareActive);
			itemActive.timeToActiveCounter = new TimeCounter(item.mTimeToActiveCounter.getTotal());
			itemActive.timeActiveCounter = new TimeCounter(item.mActiveTimeCounter.getTotal());
			itemActive.item = item.mActiveSprite;
			itemActive.isItemActive = true;
			
			if (itemActive.item != null) {
//				itemActive.cordinateActive = new Cordinate(mPlayer.getX() + (mPlayer.getWidth()-itemActive.item.getWidth())/2, mPlayer.getY() + (mPlayer.getHeight()-itemActive.item.getHeight())/2);
				itemActive.item.setZIndex(LAYER_ITEM);
				itemActive.item.setScale(0.8f);
				scene.attachChild(itemActive.item);
//				itemActive.item.setPosition(mPlayer.getX() + (mPlayer.getWidth()-itemActive.item.getWidth())/2, mPlayer.getY() + (mPlayer.getHeight()-itemActive.item.getHeight())/2);
//				setPositionItem(mPlayer, itemActive.itemPrepareActive);
				itemActive.item.setVisible(false);
				
				arrListLargeDamageItemActive.add(itemActive);
			}
			itemActive.timeToActiveCounter.start();
			if (itemActive.timeToActiveCounter.getTotal() < 0) {
				itemActive.active = true;
				scene.detachChild(itemActive.itemPrepareActive);
				itemActive.item.setVisible(true);
				
				synchronized (mPlayer) {
					itemActive.rotate_ = mPlayer.getAngle();
					itemActive.item.setCurrentTileIndex((int)itemActive.rotate_[0]);
					createAnimationFromI2JByActiveLoop(itemActive.item, largeItemEffectAnimationDuration, (int)itemActive.rotate_[0], (int)(itemActive.rotate_[0]+7), false);
					itemActive.item.setRotation(itemActive.rotate_[2]);
				}
				
			}else {
				itemActive.active = !itemActive.timeToActiveCounter.update(pSecondsElapsed);	
			}
			
			if (itemActive.active) {
				scene.detachChild(itemActive.itemPrepareActive);
				itemActive.item.setVisible(true);
				setPositionItem(mPlayer, itemActive.item);
				itemActive.timeActiveCounter.start();
				synchronized (mPlayer) {
					itemActive.rotate_ = mPlayer.getAngle();
					itemActive.item.setCurrentTileIndex((int)itemActive.rotate_[0]);
					createAnimationFromI2JByActiveLoop(itemActive.item, largeItemEffectAnimationDuration, (int)itemActive.rotate_[0], (int)(itemActive.rotate_[0]+7), false);
					
					itemActive.item.setRotation(itemActive.rotate_[2]);
				}
				if (itemActive.item != null) {
					float v0 = (float) Math.sqrt(mPlayer.getVelocity().x * mPlayer.getVelocity().x + mPlayer.getVelocity().y * mPlayer.getVelocity().y);
					float rateX = mPlayer.getVelocity().x / v0;
					float rateY = mPlayer.getVelocity().y / v0;
					itemActive.velocity = new Vector2();
					itemActive.velocity.x = rateX * mSpeed;
					itemActive.velocity.y = rateY * mSpeed;
					itemActive.update(pSecondsElapsed);
				}
			}
		}
	}
	
	private void effectWhenCollision(){
		// Sound play when collision
		if (enableBgSound) {
			bgSound.play();
		}
		// End sound play
		// Vibrate when collision
		if(enableVibrate){
			Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vibrator.vibrate(500);
		}
		// End vibrate when collision
	}
	
	public boolean calcEmptyPosition(IShape pShape) {
		float x, y;
		while (true) {
			x = (float)Math.random() * CAMERA_WIDTH;
			y = (float)Math.random() * CAMERA_HEIGHT;
			if (x - pShape.getWidth() < 0) {
				x = pShape.getWidth();
			}
			if (x + pShape.getWidth() > CAMERA_WIDTH) {
				x = CAMERA_WIDTH - pShape.getWidth();
			}
			if (y - pShape.getHeight() < 0) {
				y = pShape.getHeight();
			}
			if (y + pShape.getHeight() > CAMERA_HEIGHT) {
				y = CAMERA_HEIGHT - pShape.getHeight();
			}
			pShape.setPosition(x, y);

			if (!(pShape.collidesWith(mPlayer))) {
				return true;
			}
		}
	}
	
	void updateCreeps(float pSecondsElapsed) {
		
		for (int i = arrListActiveEnemy.size()-1; i >= 0; i--) {
			Creature creep = arrListActiveEnemy.get(i);
			
			if (creep.timeToChangeTarget.getTotal() <= 0 || !creep.timeToChangeTarget.update(pSecondsElapsed)) {
				synchronized (mPlayer) {
					creep.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					creep.timeToChangeTarget.start();
				}
			}
			
//			float dx = mPlayer.getX() - creep.getX();
//			float dy = mPlayer.getY() - creep.getY();
			float dx = creep.cordinate.x - creep.getX();
			float dy = creep.cordinate.y - creep.getY();
			float r = 0.7f * enemySpeed / ((float) Math.sqrt(dx * dx + dy * dy));
			creep.setVelocity(dx * r, dy * r);

			creep.processOnGround(mCamera.getWidth(), mCamera.getHeight(),
					pSecondsElapsed);

			if (creep.checkCollision(mPlayer, pSecondsElapsed)) {
				gameOver();
			}

			creep.update(pSecondsElapsed);
		}
	}
	
	void updateCreepsLineEnemy(float pSecondsElapsed) {

		//		int size = arrLineEnemy.size();
		//		test.setText(String.valueOf(System.currentTimeMillis()));

		for (int i = 0; i < arrLineEnemy.size(); i++) {
			Enemy enemy = arrLineEnemy.get(i);
			Creature creep = enemy.creature;
			Cordinate cordinate = enemy.cordinate;

			if (creep.checkCollision(mPlayer, pSecondsElapsed)) {
				gameOver();
			}

			float dx = cordinate.x - creep.getX();
			float dy = cordinate.y - creep.getY();
			float r = 2*enemySpeed / ((float) Math.sqrt(dx * dx + dy * dy));
			creep.setVelocity(dx * r, dy * r);
			creep.update(pSecondsElapsed);
			
			switch (enemy.corNumberStart) {
			case 1:
				if (creep.getX() >= CAMERA_WIDTH || creep.getY() >= CAMERA_HEIGHT) {

					synchronized (enemy) {
						//						size--;
						arrLineEnemy.remove(i);
						arrListActiveEnemy.add(creep);
						creep.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					}
				}
				break;
			case 2:
				if (creep.getX() <= 0 || creep.getY() >= CAMERA_HEIGHT) {
					synchronized (enemy) {
						//						size--;
						arrLineEnemy.remove(i);
						arrListActiveEnemy.add(creep);
						creep.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					}
				}
				break;
			case 3:
				if (creep.getX() <= 0 || creep.getY() <= 0) {
					synchronized (enemy) {
						//						size--;
						arrLineEnemy.remove(i);
						arrListActiveEnemy.add(creep);
						creep.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					}
				}
				break;
			case 4:
				if (creep.getX() >= CAMERA_WIDTH || creep.getY() <= 0) {
					synchronized (enemy) {
						//						size--;
						arrLineEnemy.remove(i);
						arrListActiveEnemy.add(creep);
						creep.cordinate = new Cordinate(mPlayer.getX(), mPlayer.getY());
					}
				}
				break;
			}
		}
	}
	
	float mAccelX = 40f;
	float mAccelY = 40f;
	float mAccelZ = 40f;

	public void onAccelerometerChanged(AccelerometerData pAccelerometerData) {

		double x[] = { pAccelerometerData.getX(), pAccelerometerData.getY(),
				pAccelerometerData.getZ() };
		double y[] = new double[3];

		if (mRotateState == ROTATE_30) {
			if (display.getRotation() == 1) {
				Rotation.rotate(Rotation.RotMat15, x, y);	
			}else {
				Rotation.rotate(Rotation.RotMat15tab2, x, y);
			}
			
			mAccelX = (float) y[1];
			mAccelY = (float) y[0];
		} else if (mRotateState == ROTATE_90) {
			Rotation.rotate(Rotation.RotMat90, x, y);
			mAccelX = (float) y[1];
			mAccelY = (float) y[0];
		} else if (mRotateState == ROTATE_150) {
			Rotation.rotate(Rotation.RotMat150, x, y);
			mAccelX = (float) y[1];
			mAccelY = (float) y[0];
		} else {
			mAccelX = (float) x[1];
			mAccelY = (float) x[0];
		}

		float dist = (float) Math.sqrt(mAccelX * mAccelX + mAccelY * mAccelY);
//		if (dist < 1.0) {
//			mAccelX = 0;
//			mAccelY = 0;
//		}

		float r = 0.5f * mSpeed * dist/* /() */;
//		if (crazyPlayer) r *= crazyRate;
		float vx = mAccelX * r;
		float vy = mAccelY * r;
		float v0 = (float) Math.sqrt(vx * vx + vy * vy);
		if (v0 > maxSpeed) {
			rateVelocity = maxSpeed / v0;
			vx = vx * rateVelocity;
			vy = vy * rateVelocity;
		}
		mPlayer.setVelocity(vx, vy);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)  {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			Log.w("STATUS_GAME_CURRENT", String.valueOf(STATUS_GAME_CURRENT));
//			if (STATUS_GAME_CURRENT) {
				if (mEngine.isRunning()) {
					if (bgMusic.isPlaying()) {
						bgMusic.stop();
					}
//					if (bgSound.) {
//						
//					}
					mEngine.stop();
					scene.clearChildScene();
				}
//				else {
//					
//				}
//				onDestroy();
				finish();
				startActivity(new Intent(getBaseContext(), ChoseCharacterAndMapActivity.class));
//			}
//			else {
//				finish();
//				startActivity(new Intent(getBaseContext(), StartGame.class));
//			}
			
			return true;
		}

		if (keyCode == KeyEvent.KEYCODE_MENU
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
			pauseGame();
			return true;
		}
		
		return super.onKeyDown(keyCode, event);
	}
	
	private void createAnimationFromI2JByCountLoop(AnimatedSprite animatedSprite, long[] durationAnimation, int index1, int index2, int countLoop){
		int min, max;
		
		min = index1 < index2 ? index1 : index2;
		max = index1 >= index2 ? index1 : index2;
		
		long[] animationDurationFromI2J = new long[max - min + 1];
		
		for (int i = min; i <= max; i++) {
			animationDurationFromI2J[i-min] = durationAnimation[i];
		}

		animatedSprite.animate(animationDurationFromI2J, min, max, countLoop);
	}
	
	private void createAnimationFromI2JByActiveLoop(AnimatedSprite animatedSprite, long[] durationAnimation, int index1, int index2, boolean activeLoop){
		int min, max;
		
		min = index1 < index2 ? index1 : index2;
		max = index1 >= index2 ? index1 : index2;
		
		long[] animationDurationFromI2J = new long[max - min + 1];
		
		for (int i = min; i <= max; i++) {
			animationDurationFromI2J[i-min] = durationAnimation[i];
		}
		animatedSprite.animate(animationDurationFromI2J, min, max, activeLoop);
	}
	
	private void setPositionItem(Creature creature, AnimatedSprite item){
		synchronized (creature) {
			Vector2 v = creature.getVelocity();
			
			float distance = (creature.getWidthScaled()/2 + item.getWidthScaled()/2)/2 ;
					
			float pX = (float)((creature.getX() + creature.getWidthScaled()/2) + distance * v.x / (Math.sqrt(v.x * v.x + v.y * v.y))) - item.getWidthScaled()/2;
			float pY = (float)((creature.getY() + creature.getHeightScaled()/2) + distance * v.y / (Math.sqrt(v.x * v.x + v.y * v.y)))  - item.getHeightScaled()/2;
			
			item.setPosition(pX, pY);
		}
	}
	
	public void onLoadComplete() {

	}

}